#!/bin/bash
# install kubernetes
# 网址: https://kubernetes.io https://mirantis.github.io/cri-dockerd/
# 下载: https://www.downloadkubernetes.com

#1查找我的函数文件
search_public_functions() {
        #输入函数文件名称
        functions_name="public_functions"
        #获取函数文件名称路径
        functions_url="$(sudo find / -path /proc -prune -o -name ${functions_name} -print)"
        #查找函数文件并加载
        if [ -n "${functions_url}" ]; then
                for i in "${functions_url}"; do
                        #加载文件
                        . $i
                done
        else
                echo "Not fount ${functions_name}"
                exit 1
        fi
}
search_public_functions

#2获取系统类型
get_distribution() {
        lsb_dist=""
        # Every system that we officially support has /etc/os-release
        if [ -r /etc/os-release ]; then
                lsb_dist="$(. /etc/os-release && echo "$ID")"
        fi
        # Returning an empty string here should be alright since the
        # case statements don't act unless you provide an actual value
        echo "${lsb_dist}"
}

#基于校验和文件，验证本目录下可执行文件
if [ "$(get_distribution)" == "centos" ]; then
	logW "--- 基于校验和文件，验证本目录下可执行文件"
	for i in $(file * | grep LSB | cut -d: -f1)
	do
		echo "$(cat .${i}.sha256) $i" | sha256sum --check
	done
	echo
fi

#安装kubelet kubeadm kubectl kubectl-convert
install_Kubetools_binary() {
	INSTALL_DIR="/usr/local/bin"
	SERVICE_DIR="/usr/lib/systemd/system"

	for i in kubelet kubeadm kubectl kubectl-convert; do
		if [[ -f $i ]]; then
			sudo install -o root -g root -m 0755 $i ${INSTALL_DIR}/$i
		else
			echo -e "file $i Not found\n"
			exit 1
		fi
	done

	cat <<-EOF | sudo tee ${SERVICE_DIR}/kubelet.service
		[Unit]
		Description=kubelet: The Kubernetes Node Agent
		Documentation=https://kubernetes.io/docs/
		Wants=network-online.target
		After=network-online.target

		[Service]
		ExecStart=/usr/bin/kubelet
		Restart=always
		StartLimitInterval=0
		RestartSec=10

		[Install]
		WantedBy=multi-user.target
	EOF

	mkdir -p ${SERVICE_DIR}/kubelet.service.d/
	cat <<-EOF | sudo tee ${SERVICE_DIR}/kubelet.service.d/10-kubeadm.conf
		# Note: This dropin only works with kubeadm and kubelet v1.11+
		[Service]
		Environment="KUBELET_KUBECONFIG_ARGS=--bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf"
		Environment="KUBELET_CONFIG_ARGS=--config=/var/lib/kubelet/config.yaml"
		# This is a file that "kubeadm init" and "kubeadm join" generates at runtime, populating the KUBELET_KUBEADM_ARGS variable dynamically
		EnvironmentFile=-/var/lib/kubelet/kubeadm-flags.env
		# This is a file that the user can use for overrides of the kubelet args as a last resort. Preferably, the user should use
		# the .NodeRegistration.KubeletExtraArgs object in the configuration files instead. KUBELET_EXTRA_ARGS should be sourced from this file.
		EnvironmentFile=-/etc/sysconfig/kubelet
		ExecStart=
		ExecStart=/usr/bin/kubelet \$KUBELET_KUBECONFIG_ARGS \$KUBELET_CONFIG_ARGS \$KUBELET_KUBEADM_ARGS \$KUBELET_EXTRA_ARGS
	EOF

	systemctl enable kubelet
	#  kubectl version --client --output=yaml
	#  kubectl convert --help | head -20
}

#安装kubelet kubeadm kubectl
install_Kubetools_repo() {
	kubernetes_version='v1.31'
	if [ "$(get_distribution)" == "centos" ]; then
		logW "--- 创建配置文件 /etc/yum.repos.d/kubernetes.repo"
		cat <<-EOF | sudo tee /etc/yum.repos.d/kubernetes.repo
			[kubernetes]
			name=Kubernetes
			baseurl=https://pkgs.k8s.io/core:/stable:/v1.31/rpm/
			enabled=1
			gpgcheck=0
			#gpgkey=https://pkgs.k8s.io/core:/stable:/v1.31/rpm/repodata/repomd.xml.key
			exclude=kubelet kubeadm kubectl cri-tools kubernetes-cni
		EOF
		yum clean all
		yum install -y kubelet kubeadm kubectl --disableexcludes=kubernetes
	elif [ "$(get_distribution)" == "ubuntu" ]; then
		sudo apt-get update
		sudo apt-get install -y apt-transport-https ca-certificates curl gpg
		sudo mkdir -p -m 755 /etc/apt/keyrings
		sudo curl -fsSL https://mirrors.aliyun.com/kubernetes-new/core/stable/${kubernetes_version}/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
		#sudo curl -fsSL https://pkgs.k8s.io/core:/stable:/${kubernetes_version}/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
		echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://mirrors.aliyun.com/kubernetes-new/core/stable/${kubernetes_version}/deb/ /" | sudo tee /etc/apt/sources.list.d/kubernetes.list
		sudo apt-get update
		sudo apt-get install -y kubelet kubeadm kubectl
		#锁定软件
		sudo apt-mark hold kubelet kubeadm kubectl
	fi

	logW "设置kubelet开机启动"
	logY "sudo systemctl enable kubelet"
		sudo systemctl enable kubelet
		checkTF
}
install_Kubetools_repo

#启动kubectl自动补全功能
bash_Completion_kube () {
	logW "--- 启动kubectl自动补全功能"
		sudo source /usr/share/bash-completion/bash_completion &>/dev/null
		if [[ $? -eq 0 ]]; then
			sudo kubectl completion bash | sudo tee /etc/bash_completion.d/kubectl >/dev/null
			sudo chmod a+r /etc/bash_completion.d/kubectl
			sudo kubeadm completion bash | sudo tee /etc/bash_completion.d/kubeadm >/dev/null
			sudo chmod a+r /etc/bash_completion.d/kubeadm
			sudo source /usr/share/bash-completion/bash_completion &>/dev/null
		else
			echo -e "software bash-completion Not installed\n"
			exit 1
		fi
}
bash_Completion_kube

#安装cri-dockerd
install_Cri_dockerd() {
	DIR='cri-dockerd'
	sudo tar -zxf cri-dockerd-0.3.14.amd64.tgz
	sudo install -o root -g root -m 0755 $DIR/cri-dockerd /usr/local/bin/cri-dockerd
	sudo install $DIR/cri-docker.service /etc/systemd/system
	sudo install $DIR/cri-docker.socket /etc/systemd/system
	logW "启动cri-docker"
	logY "systemctl enable --now cri-docker.socket"
	sudo systemctl daemon-reload
	sudo systemctl enable --now cri-docker.socket
	sudo systemctl status cri-docker.socket
}
install_Cri_dockerd


# kubeadm init --ignore-preflight-errors=NumCPU --config=kubeadm-init.yaml | tee master-init.log

#初始化
# kubeadm init --control-plane-endpoint="master1" --kubernetes-version=v1.31.0 --pod-network-cidr=10.244.0.0/16 --service-cidr=10.96.0.0/12 --token-ttl=0 --cri-socket unix:///run/cri-dockerd.sock --upload-certs --image-repository=121.40.150.234:5000

#cri-docker配置
# [service]
# ExecStart=/usr/local/bin/cri-dockerd --container-runtime-endpoint fd:// --network-plugin=cni --cni-bin-dir=/opt/cni/bin --cni-cache-dir=/var/lib/cni/cache --cni-conf-dir=/etc/cni/net.d --pod-infra-container-image=registry.aliyuncs.com/google_containers/pause:3.10

#忽略swap启用的状态错误
#/etc/default/kubelet
#KUBELET_EXTRA_ARGS="--fail-swap-on=false"
